package ltd.hxya.novel.admin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ltd.hxya.novel.admin.entity.Operation;
import ltd.hxya.novel.admin.entity.User;
import ltd.hxya.novel.admin.entity.UserOperation;
import ltd.hxya.novel.admin.service.IUserService;
import ltd.hxya.novel.admin.vo.UserVo;
import ltd.hxya.novel.common.bean.Result;
import ltd.hxya.novel.springsecurity.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/admin/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        String token = userService.login(user);

        return Result.success(token);
    }

    @PostMapping("/logout")
    public Result login(){
        userService.logout();
        return Result.success();
    }

    /**
     * 查询用户信息
     */
    @GetMapping("/info")
    public Result<UserVo> info() throws ExecutionException, InterruptedException {
        UserVo userVo = userService.info();
        return Result.success(userVo);
    }

    /**
     * 查询该该用户未拥有的权限
     */
    @GetMapping("/noHasPermission")
    public Result<Page<Operation>> noHasPermission(User user){
        Page<Operation> operationPage = userService.noHasPermission(user);
        return Result.success(operationPage);
    }

    /**
     * 给用户添加权限
     */
    @PreAuthorize("@expression.hasAuthority('admin:user:add')")
    @PostMapping("/addPermission")
    public Result addPermission(UserOperation userOperation){
        //添加用户权限
        userService.addPermission(userOperation);
        return Result.success();
    }

    /**
     * 查询用户拥有的权限
     */
    @GetMapping("/hasPermission/{userId}")
    public Result<Page<Operation>> hasPermission(@PathVariable Integer userId){
        Page<Operation> operationPage = userService.hasPermission(userId);
        return Result.success(operationPage);
    }

    /**
     * 删除用户权限
     */
    @DeleteMapping("/deletePermission")
    public Result deletePermission(UserOperation userOperation){
        userService.deletePermission(userOperation);
        return Result.success();
    }


    /**
     * 用户账号禁用
     */
    @DeleteMapping("/disableAccount/{userId}")
    public Result updateAccountStatus(@RequestBody User user){
        userService.disableAccount(user);
        return Result.success();
    }

    /**
     * 管理员的添加处理
     * @param userVo
     * @return
     */
    @PostMapping("/addUser")
    @PreAuthorize("@expression.hasAuthority('*')")
    public Result addRole(@Validated @RequestBody UserVo userVo){
        userService.addUser(userVo);
        return Result.success();
    }

    /**
     * 根据id删除管理员，删除管理员的时候还要删除user_operation和user_role表
     * @param ids
     * @return
     */
    @DeleteMapping("/deleteById")
    public Result deleteById(Integer[] ids){
        userService.deleteById(ids);
        return Result.success();
    }

    /**
     * 根据adminId查询管理员
     */
    @GetMapping("/userInfo/{userId}")
    public Result<UserVo> info(@PathVariable Integer userId) throws ExecutionException, InterruptedException {
        UserVo userVo = userService.roleInfo(userId);
        return Result.success(userVo);
    }

    /**
     * Admin的修改的处理
     * @param userVo
     * @return
     */
    @PutMapping("/updateAdmin")
    @PreAuthorize("@expression.hasAuthority('*')")
    public Result updateRole(@Validated @RequestBody UserVo userVo){
        userService.updateRole(userVo);
        return Result.success();
    }


    /**
     * 修改密码的处理
     * @param user
     * @return
     */
    @PreAuthorize("@expression.hasAuthority('system:user:resetPwd')")
    @PutMapping("/resetPwd")
    public Result resetPwd(@RequestBody User user) {
        userService.checkUserAllowed(user);
        User userById = userService.getById(user.getUserId());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        userById.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.updateByUserId(userById);
        return Result.success();
    }

    /**
     * 查询用户信息，并且显示
     * @return
     */
    @GetMapping("/profile")
    public Result profile(){
        SecurityContext securityContext = SecurityUtils.getSecurityContext();
        String name = securityContext.getAuthentication().getName();
        User user = userService.getUserByUsername(name);
        UserVo userVo = new UserVo();
        return Result.success(user);
    }


    /**
     * 重置密码
     */
    @PutMapping("/updatePwd")
    public Result updatePwd(String oldPassword, String newPassword) {
        SecurityContext securityContext = SecurityUtils.getSecurityContext();
        String userName = securityContext.getAuthentication().getName();
        User user = userService.getUserByUsername(userName);
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)){
            return Result.fail(111,"修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return Result.fail(111,"新密码不能与旧密码相同");
        }
        // 重置密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.updateByUserId(user);
        return Result.success();
    }

    /**
     * 上传头像
     */
    @PostMapping("/addImage")
    public Result addImage(@RequestBody String userImage) {
        userImage = userImage.replaceAll("%3A", ":").replaceAll("%2F", "/")  //过滤URL 包含中文
                .replaceAll("%3F", "?").replaceAll("%3D", "=").replaceAll(
                        "%26", "&");
        userImage = userImage.substring(0,userImage.length()-1);      // 删掉最后一位的 '='
        SecurityContext securityContext = SecurityUtils.getSecurityContext();
        String userName = securityContext.getAuthentication().getName();
        User user = userService.getUserByUsername(userName);
        user.setImage(userImage);
        userService.updateByUserId(user);
        return Result.success();
    }

}
